<template>
    <div class="app-container">
        <div class="card-header" style="margin-bottom:20px">
            <span class="card-header-text"></span>
            <div>
                <el-button type="primary" @click="onAddRow">
                    <SvgIcon name="elementPlus" />新增
                </el-button>
                <el-button type="danger" plain :disabled="state.multiple" @click="onTabelRowDel">
                    <SvgIcon name="elementDelete" />
                    删除
                </el-button>
            </div>
        </div>
        <!--数据表格-->
        <el-table :border="false" v-loading="state.loading" :data="state.tableData"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="钩子名称" align="center" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="请求方法" align="center" prop="method" :show-overflow-tooltip="true" />
            <el-table-column label="目标地址" align="center" prop="path" :show-overflow-tooltip="true" />
            <el-table-column label="启用状态" align="center" prop="status" />

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <div style="display: flex;align-items: center;justify-content: center;gap: 10px;">
                        <div>
                            <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
                                <el-button type="primary" size="small" circlesize="small" circle
                                    @click="onOpenEditModule(scope.row)">
                                    <SvgIcon :size="12" name="elementEdit" />
                                </el-button>
                            </el-tooltip>
                        </div>
                        <div>
                            <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
                                <el-button type="danger" size="small" circlesize="small" circle
                                    @click="onTabelRowDel(scope.row)">
                                    <SvgIcon :size="12" name="elementDelete" />
                                </el-button>
                            </el-tooltip>
                        </div>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页设置-->
        <div v-show="state.total > 0">
            <el-divider></el-divider>
            <el-pagination background :total="state.total" :current-page="state.queryParams.pageNum"
                :page-size="state.queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <el-dialog v-model="state.isShowDialog" :title="state.title" width="80%" center>
            <el-form ref="ruleFormRef" :model="state.info" :rules="state.ruleRules" label-width="150px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="钩子名称" prop="name">
                            <el-input v-model="state.info.name" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="请求方法" prop="method">
                            <el-input v-model="state.info.method" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="目标地址" prop="path">
                            <el-input v-model="state.info.path" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="目标类型" prop="target">
                            <el-radio-group validate-event v-model="state.info.target">
                                <el-radio v-for="dict in state.targetOption" :key="dict.dictValue"
                                    :value="dict.dictValue">{{
                                        dict.dictLabel }} </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="启用状态" prop="status">
                            <el-radio-group validate-event v-model="state.info.status">
                                <el-radio v-for="dict in state.statusOption" :key="dict.dictValue"
                                    :value="dict.dictValue">{{
                                        dict.dictLabel }} </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submit">保 存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="JobLog">
import {
    reactive,
    onMounted,
    onUnmounted,
    ref,
    unref,
    getCurrentInstance,
    watch
} from "vue";

import { ElMessageBox, ElMessage } from "element-plus";
import { gatherId } from '@/utils/dataGather'
import { get, update, add, del } from "@/api/public/basic";
const ruleFormRef = ref<HTMLElement | null>(null);
const { proxy } = getCurrentInstance() as any;
const props = defineProps({
    curApiId: {
        type: String,
        default: '',
    }
})

const state = reactive({
    // 参数
    // 总条数
    total: 0,
    // 列表表格数据
    tableData: [],
    // 遮罩层
    loading: true,
    // 选中数组
    ids: [],
    // 非单个禁用
    single: true,
    // 非多个禁用
    multiple: true,
    // 弹出层标题
    title: "",
    // 是否显示弹出层
    isShowDialog: false,
    // 查询参数
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        apiId: ''
    },
    hookId: '',
    info: {
        status: 1
    },
    ruleRules: {
        name: [
            { required: true, message: '请输入', trigger: 'blur' }
        ],
        method: [
            { required: true, message: '请输入', trigger: 'blur' }
        ],
        path: [
            { required: true, message: '请输入', trigger: 'blur' }
        ],
        target: [
            { required: true, message: '请选择', trigger: 'change' }
        ],

    },
    targetOption: [
        {
            dictValue: 0,
            dictLabel: '脚本'
        },
        {
            dictValue: 1,
            dictLabel: '接口'
        }
    ],
    statusOption: [
        {
            dictValue: 0,
            dictLabel: '关闭'
        },
        {
            dictValue: 1,
            dictLabel: '开启'
        }
    ]
});

watch(
    () => props.curApiId,
    () => {
        console.log('00000', props.curApiId)
        if (!props.curApiId) return
        state.queryParams.apiId = props.curApiId
        handleQuery();
    },
    // { immediate: true }
);


/** 查询定时任务列表 */
const handleQuery = () => {
    state.loading = true;
    console.log('----111', state.queryParams)

    get(state.queryParams, gatherId.HOOK_LIST_ID).then((response: any) => {
        console.log('----', state.queryParams)
        state.tableData = response.data.result;
        state.total = response.data.total;
        state.loading = false;
    });
};

const onOpenEditModule = (row: any) => {
    get(row.hookId, gatherId.HOOK_LIST_ID).then((response: any) => {
        if (response.code == 200) {
            state.info = response.data[0]
            state.isShowDialog = true
        }
    });
}

const onAddRow = () => {
    state.isShowDialog = true
}
const submit = () => {
    const formWrap = unref(ruleFormRef) as any;
    if (!formWrap) return;
    formWrap.validate((valid: boolean) => {
        if (!valid) return
        const params = {
            apiId: props.curApiId,
            ...state.info
        }

        if (state.hookId) {
            // 修改
            update(params, state.hookId, gatherId.HOOK_LIST_ID).then((response: any) => {
                if (response.code == 200) {
                    ElMessage({
                        type: 'success',
                        plain: true
                    })
                    state.isShowDialog = false
                    handleQuery()
                }
            })
        } else {
            add(params, gatherId.HOOK_LIST_ID).then((response: any) => {
                if (response.code == 200) {
                    ElMessage({
                        type: 'success',
                        message: '保存成功',
                        plain: true
                    })
                    state.hookId = response.data
                    state.isShowDialog = false
                    handleQuery()
                }
            })
        }


    })

}


/** 删除按钮操作 */
const onTabelRowDel = (row: any) => {
    const ids = row.hookId ? [row.hookId] : state.ids;
    ElMessageBox({
        message: '是否确认删除?',
        title: "警告",
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(function () {
        return del({ hookId: ids }, gatherId.HOOK_LIST_ID).then((response: any) => {
            if (response.code == 200) {
                handleQuery();
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                    plain: true
                })
            }
        });
    });
};

// 多选框选中数据
const handleSelectionChange = (selection: any) => {
    state.ids = selection.map((item: any) => item.logId);
    state.single = selection.length != 1;
    state.multiple = !selection.length;
};

//分页页面大小发生变化
const handleSizeChange = (val: any) => {
    state.queryParams.pageSize = val;
    handleQuery();
};
//当前页码发生变化
const handleCurrentChange = (val: any) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

// 页面加载时调用
onMounted(() => {
    if (!props.curApiId) return
    state.queryParams.apiId = props.curApiId
    handleQuery();
});

// 页面卸载时
onUnmounted(() => {
    //   proxy.mittBus.off("onEditPostModule");
});
</script>
